package com.meiyu.live.ui.search;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.net.param.BaseBodyParams;
import com.meiyu.live.net.param.SearchParams;
import com.meiyu.live.net.response.GosearchResponse;
import com.meiyu.live.net.response.HotLiveResponse;
import com.meiyu.live.popj.LiveRoom;
import com.meiyu.live.tv.audience.AudienceActivity;
import com.meiyu.live.util.DisplayUtils;
import com.meiyu.live.widget.MSGView;
import com.meiyu.live.widget.NetLoadingDailog;
import com.meiyu.live.widget.XCFlowLayout;

import java.util.ArrayList;

/**
 * Created by zbl on 2016/8/18.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener {

    private static final int MAX_RECENT = 10;

    protected NetLoadingDailog dialog_loading;
    private MSGView msgView;
    private View btn_search, btn_back, btn_clear_recent;
    private EditText et_search;
    private XCFlowLayout flowLayout_recent, flowLayout_hot;
    private ViewGroup.MarginLayoutParams lp;
    private View layout_init;
    private ListView listView;
    private DataListAdapter adapter;

    private GosearchResponse gosearchResponse;
    private ArrayList<String> recentList = new ArrayList<>();
    private HotLiveResponse hotLiveResponse;

    private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        init();
    }

    private void init() {
        inflater = LayoutInflater.from(this);
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = DisplayUtils.dpToPixel(this, 5);
        lp.rightMargin = lp.leftMargin;
        lp.topMargin = lp.rightMargin;
        lp.bottomMargin = lp.topMargin;

        dialog_loading = new NetLoadingDailog(this);
        msgView = (MSGView) findViewById(R.id.msgView);

        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_search = findViewById(R.id.btn_search);
        btn_search.setOnClickListener(this);
        btn_clear_recent = findViewById(R.id.btn_clear_recent);
        btn_clear_recent.setOnClickListener(this);
        et_search = (EditText) findViewById(R.id.et_search);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    listView.setVisibility(View.GONE);
                    layout_init.setVisibility(View.VISIBLE);
                    msgView.dismiss();
                }
            }
        });

        flowLayout_recent = (XCFlowLayout) findViewById(R.id.flowlayout_recent);
        flowLayout_hot = (XCFlowLayout) findViewById(R.id.flowlayout_hot);

        layout_init = findViewById(R.id.layout_init);
        listView = (ListView) findViewById(R.id.listview);
        adapter = new DataListAdapter();
        listView.setAdapter(adapter);

        getHotSeachData();
        final ArrayList<String> list = gson.fromJson(UserConfig.getInstance().getRecentSearch(), ArrayList.class);
        recentList.addAll(list);
        updateRecentFlowLayout();
    }

    private void updateRecentFlowLayout() {
        flowLayout_recent.removeAllViews();
        for (String searchText : recentList) {
            SearchTextView view = new SearchTextView(this);
            view.setOnClickListener(onClickListener_recent);
            view.setData(searchText);
            flowLayout_recent.addView(view, lp);
        }
    }

    private void getHotSeachData() {
        dialog_loading.loading();
        //进入搜索界面调用接口
        request(new BaseBodyParams(Constant.UrlParams.GOSEARCH), GosearchResponse.class, new Response.Listener<GosearchResponse>() {
            @Override
            public void onResponse(GosearchResponse gosearchResponse) {
                SearchActivity.this.gosearchResponse = gosearchResponse;
                updateFlowlayout();
                dialog_loading.dismissDialog();
            }
        });
    }

    private void updateFlowlayout() {
        if (gosearchResponse != null) {
            for (String searchText : gosearchResponse.getHash()) {
                SearchTextView view = new SearchTextView(this);
                view.setOnClickListener(onClickListener_hot);
                view.setData(searchText);
                flowLayout_hot.addView(view, lp);
            }
        }
    }

    private View.OnClickListener onClickListener_recent = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SearchTextView searchTextView = (SearchTextView) view;
            et_search.setText(searchTextView.getData());
        }
    };

    private View.OnClickListener onClickListener_hot = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SearchTextView searchTextView = (SearchTextView) view;
            et_search.setText(searchTextView.getData());
        }
    };

    @Override
    public void onClick(View view) {
        if (view == btn_clear_recent) {
            recentList.clear();
            flowLayout_recent.removeAllViews();
            UserConfig.getInstance().setRecentSearch("[]");
        } else if (view == btn_search) {
            String searchText = et_search.getText().toString();
            saveRecentSearchText(searchText);
            if (!TextUtils.isEmpty(searchText)) {
                getData(searchText);
            }
        } else if (view == btn_back) {
            finish();
        }
    }

    private void saveRecentSearchText(String searchText) {
        if (!TextUtils.isEmpty(searchText)) {
            boolean isExist = false;
            for (String text : recentList) {
                if (searchText.equals(text)) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                if (recentList.size() >= MAX_RECENT) {
                    recentList.remove(recentList.size() - 1);
                }
                recentList.add(0, searchText);
                updateRecentFlowLayout();
                UserConfig.getInstance().setRecentSearch(gson.toJson(recentList));
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onError() {
        dialog_loading.dismissDialog();
        super.onError();
    }

    private void getData(String text) {
        dialog_loading.loading();
        //搜索接口
        request(new SearchParams(text), HotLiveResponse.class, new Response.Listener<HotLiveResponse>() {
            @Override
            public void onResponse(HotLiveResponse baseResponse) {
                dialog_loading.dismissDialog();
                if (baseResponse != null) {
                    SearchActivity.this.hotLiveResponse = baseResponse;
                    adapter.notifyDataSetChanged();
                    listView.setVisibility(View.VISIBLE);
                    layout_init.setVisibility(View.GONE);
                    if (hotLiveResponse.getHash().size() == 0) {
                        msgView.show_empty();
                    } else {
                        msgView.dismiss();
                    }
                } else {
                    msgView.show_error();
                    listView.setVisibility(View.VISIBLE);
                    layout_init.setVisibility(View.GONE);
                }
            }
        });
    }

    class DataListAdapter extends BaseAdapter {

        private class ViewHolder {
            ImageView[] iv_image;
            TextView[] tv_name, tv_title, tv_count;
            View[] layout_grid;
        }

        View.OnClickListener onItemClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int index = (int) view.getTag();
                final LiveRoom bean = hotLiveResponse.getHash().get(index);
                AudienceActivity.start(SearchActivity.this, bean);
            }
        };

        @Override
        public int getCount() {
            return hotLiveResponse != null && hotLiveResponse.getHash() != null ? (int) Math.ceil(((float) hotLiveResponse.getHash().size()) / 2) : 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_hotlive, null);
                holder = new ViewHolder();
                holder.iv_image = new ImageView[]{
                        (ImageView) convertView.findViewById(R.id.iv_image0),
                        (ImageView) convertView.findViewById(R.id.iv_image1)
                };
                holder.tv_name = new TextView[]{
                        (TextView) convertView.findViewById(R.id.tv_name0),
                        (TextView) convertView.findViewById(R.id.tv_name1)
                };
                holder.tv_count = new TextView[]{
                        (TextView) convertView.findViewById(R.id.tv_count0),
                        (TextView) convertView.findViewById(R.id.tv_count1)
                };
                holder.tv_title = new TextView[]{
                        (TextView) convertView.findViewById(R.id.tv_title0),
                        (TextView) convertView.findViewById(R.id.tv_title1)
                };
                holder.layout_grid = new View[]{
                        convertView.findViewById(R.id.layout_grid0),
                        convertView.findViewById(R.id.layout_grid1)
                };
                holder.layout_grid[0].setOnClickListener(onItemClickListener);
                holder.layout_grid[1].setOnClickListener(onItemClickListener);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            for (int i = 0; i < 2; i++) {
                int index = position * 2 + i;
                holder.layout_grid[i].setTag(index);
                if (index >= hotLiveResponse.getHash().size()) {
                    holder.layout_grid[i].setVisibility(View.INVISIBLE);
                } else {
                    holder.layout_grid[i].setVisibility(View.VISIBLE);
                    final LiveRoom bean = hotLiveResponse.getHash().get(index);
                    imageLoader.displayImage(bean.getImage_url(), holder.iv_image[i], options);
                    holder.tv_title[i].setText(bean.getDescription());
                    holder.tv_name[i].setText(bean.getAnchor_name());
                    holder.tv_count[i].setText("" + bean.getViewer_num());
                }
            }
            return convertView;
        }
    }
}
